<template>
	<div class="TUIChat" :class="[!isPC ? 'TUIChat-H5' : '']">
		<!--   <image
			v-if="isChat"
            src="https://xbb.fuliaoxx.com/img/call/call-viceo.png"
            mode="widthFix"
            style="position: fixed; bottom: 130px; right: 10px; width: 200rpx; z-index: 999"
            @click="callVideo"
        ></image>
		<image
			v-if="userGenderMan"
			style="position: fixed; bottom: 200px; right: 10px; width: 200rpx; width: 120rpx; height: 120rpx; z-index: 999"
			src="/static/top-up.png" @click="fto('/pages/my/wallet')"></image>
        <view
            v-if="intimacy != 0"
            style="
                position: fixed;
                top: 130px;
                right: 0px;
                z-index: 999;
                background: white;
                border-radius: 40px 0 0 40px;
                padding: 10rpx 18rpx;
                display: flex;
                align-items: center;
                justify-content: center;
            "
        >
            <image
                class="heart"
                src="https://xbb.fuliaoxx.com/img/call/heart.png"
                style="width: 50rpx; margin-right: 6rpx"
            >
            </image>
            <text style="font-width: bold"> {{ intimacy }}°C </text>
        </view> -->
		<div class="TUIChat-main" style="background: #eeeeee">
			<!--     <div class="TUIChat-safe-tips">
        <span> 
          {{
            TUITranslateService.t(
              "TUIChat.【安全提示】本 APP 仅用于体验腾讯云即时通信 IM 产品功能，不可用于业务洽谈与拓展。请勿轻信汇款、中奖等涉及钱款的信息，勿轻易拨打陌生电话，谨防上当受骗。"
            )
          }}
        </span>
        <a @click="openComplaintLink(Link.complaint)">{{
          TUITranslateService.t("TUIChat.点此投诉")
        }}</a>
      </div> -->
			<div class="TUIChat-application-tips" v-if="isGroup && groupApplicationCount > 0"
				@click="toggleApplicationList()">
				<span>{{ groupApplicationCount }}
					{{ TUITranslateService.t('TUIChat.条入群申请') }}
					<span class="application-tips-btn">{{
                        TUITranslateService.t('TUIChat.点击处理')
                    }}</span>
				</span>
			</div>
			<scroll-view class="TUI-message-list" scroll-y="true" :scroll-top="scrollTop">
				<p class="message-more" @click="getHistoryMessageList" v-if="!isCompleted">
					{{ TUITranslateService.t('TUIChat.查看更多') }}
				</p>
				<li v-for="(item, index) in messageList" :key="item.vueForRenderKey" :id="item.ID" ref="messageAimID"
					class="message-li">
					<template >
						<MessageTimestamp :currTime="item.time" :prevTime="index > 0 ? messageList[index - 1].time : 0">
						</MessageTimestamp>
						<div class="message-item" @click.stop="toggleID = ''">
							<MessageTip v-if="
                                    item.type === TYPES.MSG_GRP_TIP || isCreateGroupCustomMessage(item)
                                " :content="item.getMessageContent()" />
							<div v-else-if="!item.isRevoked && !item.getSignalingInfo()||item.cloudCustomData"
								@longpress="handleToggleMessageItem($event, item, index, true)"
								@touchstart="handleH5LongPress($event, item, index, 'touchstart')"
								@touchend="handleH5LongPress($event, item, index, 'touchend')"
								@mouseover="handleH5LongPress($event, item, index, 'touchend')">
								<!--      <div
                                    v-if="
                                        item.type === TYPES.MSG_TEXT &&
                                        item.cloudCustomData == 'gift' &&
                                        !JSON.parse(item.payload.text).unShow
                                    "
                                    style="text-align: center; color: #888"
                                    @click="handleGift(item)"
                                >
                                    {{ item.flow == 'out' ? '已成功送出' : '收到' }}
                                    <span style="color: black" v-if="item.flow != 'out'">{{
                                        item.nick
                                    }}</span>
                                    {{ item.flow == 'out' ? '' : '送' }}
                                    <span v-if="item.flow != 'out'">的 </span>
                                    <span style="color: #fd8255"
                                        >{{ JSON.parse(item.payload.text).name }}
                                    </span>
                                    <span
                                        style="color: #00afff; margin-left: 5px"
                                        @click="showGift(item.payload.text)"
                                        >点击查看</span
                                    >
                                </div> -->
								<!-- 	<VideoVoice v-if="item.type === TYPES.MSG_CUSTOM&&item.cloudCustomData=='voc'" :content="item.getMessageContent()"
                        			:messageItem="item" /> -->
								<div v-if="item.payload.extension=='initNotice'"
									style="text-align: center;color: #888;">
									通过
									<span style="color: #fd8255">
										[{{item.payload.data.length>10?(item.payload.data.substring(0,10)+'...'):item.payload.data}}
									]</span>
									进入
								</div>
								<MessageBubble :messageItem="item" v-if="!item.payload.extension"
									:content="item.getMessageContent()" @resendMessage="resendMessage(item)">
									<MessageText v-if="
                                            item.type === TYPES.MSG_TEXT &&
                                            item.cloudCustomData != 'call' &&
                                            item.cloudCustomData != 'uncall'
                                        " :content="item.getMessageContent()" />

									<!-- 	<div v-if="item.type === TYPES.MSG_TEXT&&item.cloudCustomData=='call'">
                        				发起{{item.payload.text.includes('text')? JSON.parse(item.payload.text).text:item.payload.text }}
                        			</div> -->

									<div v-if="
                                            item.type === TYPES.MSG_TEXT &&
                                            item.cloudCustomData == 'uncall'
                                        ">
										通话时长:{{ item.payload.text }}
									</div>
									<ProgressMessage v-if="item.type === TYPES.MSG_IMAGE"
										:content="item.getMessageContent()" :messageItem="item">
										<MessageImage :content="item.getMessageContent()" :messageItem="item"
											@previewImage="handleImagePreview" />
									</ProgressMessage>
									<MessageVideo v-if="item.type === TYPES.MSG_VIDEO"
										:content="item.getMessageContent()" :messageItem="item" :isPC="isPC" />
									<MessageAudio v-if="item.type === TYPES.MSG_AUDIO"
										:content="item.getMessageContent()" :messageItem="item" />
									<MessageFile v-if="item.type === TYPES.MSG_FILE"
										:content="item.getMessageContent()" />
									<MessageFace v-if="item.type === TYPES.MSG_FACE" :content="item.getMessageContent()"
										:isPC="isPC" />
									<MessageLocation v-if="item.type === TYPES.MSG_LOCATION"
										:content="item.getMessageContent()" />
									<MessageCustom v-if="item.type === TYPES.MSG_CUSTOM"
										:content="item.getMessageContent()" :messageItem="item" />
								</MessageBubble>
							</div>
							<MessagePlugin v-else-if="!item.isRevoked && item.getSignalingInfo()" :message="item"
								@resendMessage="resendMessage" @handleToggleMessageItem="handleToggleMessageItem"
								@handleH5LongPress="handleH5LongPress" />
							<MessageRevoked v-else :isEdit="item.type === TYPES.MSG_TEXT" :messageItem="item"
								@messageEdit="handleEdit(item)" />

							<MessageTool :class="[
                                    'message-tool',
                                    item.flow === 'out' ? 'message-tool-out' : 'message-tool-in'
                                ]" :messageItem="item" v-if="item.ID === toggleID" />
						</div>
					</template>
				</li>
			</scroll-view>
			<Dialog v-if="reSendDialogShow" :show="reSendDialogShow" :isH5="!isPC" :center="true" :isHeaderShow="isPC"
				@submit="resendMessageConfirm()" @update:show="e => (reSendDialogShow = e)">
				<p class="delDialog-title">
					{{ TUITranslateService.t('TUIChat.确认重发该消息？') }}
				</p>
			</Dialog>
			<ImagePreviewer v-if="showImagePreview" :currentImage="currentImagePreview" :imageList="imageMessageList"
				@close="onImagePreviewerClose"></ImagePreviewer>
			<MessageGroupSystem v-if="showGroupApplication" :groupID="groupID"
				@toggleApplicationList="toggleApplicationList" @handleGroupApplication="handleGroupApplication">
			</MessageGroupSystem>
			<view class="arrearage-bg" v-if="chongzhi" :style="{ position: 'fixed', height: '100vh', width: '750rpx' }">
				<image @click="fto('/pages/my/wallet')" class="arrearage"
					src="https://xbb.fuliaoxx.com/img/call/arrearage.png" mode="widthFix">
				</image>
			</view>
		</div>
	</div>
</template>
<script lang="ts" setup>
	import { ref, computed, onUnmounted } from '../../../adapter-vue'
	import TUIChatEngine, {
		TUIGlobal,
		IMessageModel,
		TUIStore,
		StoreName,
		TUITranslateService,
		TUIChatService,
		TUIGroupService
	} from '@tencentcloud/chat-uikit-engine'

	import Link from './link'
	import MessageText from './message-elements/message-text.vue'
	import ProgressMessage from '../../common/ProgressMessage/index.vue'
	import MessageImage from './message-elements/message-image.vue'
	import MessageAudio from './message-elements/message-audio.vue'
	import MessageFile from './message-elements/message-file.vue'
	import MessageFace from './message-elements/message-face.vue'
	import MessageCustom from './message-elements/message-custom.vue'
	import MessageTip from './message-elements/message-tip.vue'
	import MessageBubble from './message-elements/message-bubble.vue'
	import MessageLocation from './message-elements/message-location.vue'
	import MessageTimestamp from './message-elements/message-timestamp.vue'
	import MessageVideo from './message-elements/message-video.vue'
	import MessageTool from './message-tool/index.vue'
	import MessageRevoked from './message-tool/message-revoked.vue'
	import MessageGroupSystem from './message-elements/message-group-system.vue'
	import MessagePlugin from '../../../plugins/plugin-components/message-plugin.vue'

	import Dialog from '../../common/Dialog/index.vue'
	import ImagePreviewer from '../../common/ImagePreviewer/index.vue'
	import { isCreateGroupCustomMessage } from '../utils/utils'
	import store from '@/store'

	// import api from '@/api/_api'

	const intimacy = ref(0)

	// api.intimacy({
	//     womanId: uni.$user.conversation
	// }).then(r => {
	//     const {
	//         data: { data }
	//     } = r
	//     intimacy.value = data.intimacy
	// })

	// import VideoVoice from  "./message-elements/video-voice.vue";
	const props = defineProps({
		groupID: {
			type: String,
			default: ''
		},
		isChat: {
			type: Boolean,
			default: false
		},
		isGroup: {
			type: Boolean,
			default: false
		}
	})
	const isPC = ref(TUIGlobal.getPlatform() === 'pc')
	const isH5 = ref(TUIGlobal.getPlatform() === 'h5')
	const messageListRef = ref()
	const title = ref('TUIChat')
	const messageList = ref()
	const isCompleted = ref(false)
	const currentConversationID = ref('')
	const nextReqMessageID = ref()
	const toggleID = ref('')
	const scrollTop = ref(5000) // 首次是 15 条消息，最大消息高度为300
	const TYPES = ref(TUIChatEngine.TYPES)
	const listRef = ref()
	const isLoadMessage = ref(false)
	const isLongpressing = ref(false)
	const chongzhi = ref(false)

	// 加群申请系统消息
	const groupApplicationCount = ref(0)
	const showGroupApplication = ref(false)
	const applicationUserIDList = ref([])

	// 消息重发 Dialog
	const reSendDialogShow = ref(false)
	const resendMessageData = ref()
	const emits = defineEmits(['handleEditor'])

	// 图片预览相关
	const showImagePreview = ref(false)
	const currentImagePreview = ref<typeof IMessageModel>()
	const imageMessageList = computed(() =>
		messageList?.value?.filter((item : typeof IMessageModel) => {
			return !item.isRevoked && item.type === TYPES.value.MSG_IMAGE
		})
	)
	// 消息滑动到底部，建议搭配 nextTick 使用
	const scrollToBottom = () => {
		// 文本消息高度：60, 最大消息高度 280
		scrollTop.value += 300
		// 解决 uniapp 打包到 app 首次进入滑动到底部，300 可设置
		const timer = setTimeout(() => {
			scrollTop.value += 1
			clearTimeout(timer)
		}, 300)
	}
	const userGenderMan = computed(() => {
		const { gender } = store.state && store.state?.user?.userInfo || {};
		return gender ? gender === 1 : false
	})
	// 监听回调函数
	const onCurrentConversationIDUpdated = (conversationID : string) => {
		console.log('conversationID', conversationID)
		currentConversationID.value = conversationID
		TUIGroupService.getGroupApplicationList().then((res : any) => {
			const applicationList = res.data.applicationList.filter(
				(application : any) => application.groupID === props.groupID
			)
			applicationUserIDList.value = applicationList.map((application : any) => {
				return application.applicationType === 0 ? application.applicant : application.userID
			})
			TUIStore.update(StoreName.CUSTOM, 'groupApplicationCount', applicationList.length)
		})
	}

	// operationType 操作类型 1: 有用户申请加群   23: 普通群成员邀请用户进群
	const onGroupSystemNoticeList = (list : Array<typeof IMessageModel>) => {
		const systemNoticeList = list.filter(message => {
			const { operationType } = message.payload
			return (operationType === 1 || operationType === 23) && message.to === props.groupID
		})

		systemNoticeList.forEach(systemNotice => {
			const { operationType } = systemNotice.payload
			if (operationType === 1) {
				const { operatorID } = systemNotice.payload
				if (!applicationUserIDList.value.includes(operatorID)) {
					applicationUserIDList.value.push(operatorID)
				}
			}
			if (operationType === 23) {
				const { inviteeList } = systemNotice.payload
				inviteeList.forEach(invitee => {
					if (!applicationUserIDList.value.includes(invitee)) {
						applicationUserIDList.value.push(invitee)
					}
				})
			}
		})
		const applicationCount = applicationUserIDList.value.length
		TUIStore.update(StoreName.CUSTOM, 'groupApplicationCount', applicationCount)
	}
	const initGift = (list : any) => {
		if (list && list.length >= 1) {
			console.log('1')
			if (list.some((v : any) => v.cloudCustomData == 'gift')) {
				store.dispatch('user/showGift')
			}
		}
	}
	setTimeout(() => {
		initGift(messageList.value)
	}, 500)
	// 消息列表监听
	TUIStore.watch(StoreName.CHAT, {
		messageList: (list : Array<typeof IMessageModel>) => {
			messageList.value = list
				.filter(
					message =>
						!message.isDeleted &&
						message.payload.text != 'none' &&
						message.cloudCustomData != 'call'
				)
				.map(message => {
					message.vueForRenderKey = `${message.ID}`
					return message
				})
			console.log(messageList)
			// 点击加载更多的消息不需要滑动到底部
			if (!isLoadMessage.value) {
				scrollToBottom()
			}
		},
		isCompleted: (flag : boolean) => {
			isCompleted.value = flag
		}
	})

	TUIStore.watch(StoreName.CONV, {
		currentConversationID: onCurrentConversationIDUpdated
	})

	// 群系统消息
	TUIStore.watch(StoreName.GRP, {
		groupSystemNoticeList: onGroupSystemNoticeList
	})

	// 群系统消息数量
	TUIStore.watch(StoreName.CUSTOM, {
		groupApplicationCount: (count : Number) => {
			groupApplicationCount.value = count
		}
	})

	// 取消监听
	onUnmounted(() => {
		TUIStore.unwatch(StoreName.CONV, {
			currentConversationID: onCurrentConversationIDUpdated
		})
		// 群系统消息
		TUIStore.unwatch(StoreName.GRP, {
			groupSystemNoticeList: onGroupSystemNoticeList
		})
	})

	// 获取历史消息
	const getHistoryMessageList = () => {
		isLoadMessage.value = true
		TUIChatService.getMessageList().then((res : any) => {
			const { nextReqMessageID: ID } = res.data
			nextReqMessageID.value = ID
			isLoadMessage.value = false
		})
	}

	const toggleApplicationList = () => {
		showGroupApplication.value = !showGroupApplication.value
	}

	const handleGroupApplication = (userID : string) => {
		const index = applicationUserIDList.value.indexOf(userID)
		if (index !== -1) {
			applicationUserIDList.value.splice(index, 1)
		}
	}
	// todo: webview 跳转
	const openComplaintLink = (type : any) => { }

	// 消息操作
	const handleToggleMessageItem = (
		e : any,
		message : typeof IMessageModel,
		index : number,
		isLongpress = false
	) => {
		if (isLongpress) {
			isLongpressing.value = true
		}
		toggleID.value = message.ID
	}

	// h5 long press
	let timer : number
	const handleH5LongPress = (e : any, message : typeof IMessageModel, index : number, type : string) => {
		if (!isH5.value) return
		function longPressHandler() {
			clearTimeout(timer)
			handleToggleMessageItem(e, message, index, true)
		}
		function touchStartHandler() {
			timer = setTimeout(longPressHandler, 500)
		}
		function touchEndHandler() {
			clearTimeout(timer)
		}
		switch (type) {
			case 'touchstart':
				touchStartHandler()
				break
			case 'touchend':
				touchEndHandler()
				setTimeout(() => {
					isLongpressing.value = false
				}, 200)
				break
		}
	}

	// 消息撤回后，编辑消息
	const handleEdit = (message : typeof IMessageModel) => {
		emits('handleEditor', message, 'reedit')
	}

	// 重发消息
	const resendMessage = (message : typeof IMessageModel) => {
		reSendDialogShow.value = true
		resendMessageData.value = message
	}

	// 图片预览
	// 开启图片预览
	const handleImagePreview = (message : typeof IMessageModel) => {
		if (showImagePreview.value || currentImagePreview.value || isLongpressing.value) {
			return
		}
		showImagePreview.value = true
		currentImagePreview.value = message
	}
	// 关闭图片预览
	const onImagePreviewerClose = () => {
		showImagePreview.value = false
		setTimeout(() => {
			currentImagePreview.value = null
		}, 50)
	}

	const resendMessageConfirm = () => {
		reSendDialogShow.value = !reSendDialogShow.value
		const messageModel = resendMessageData.value
		messageModel.resendMessage()
	}

	const handleGift = (item : any) => {
		store.dispatch('user/showGift')
	}

	const callVideo = res => {
		store.dispatch('user/CallTUICallKit', {
			type: 2
		})
	}

	const showGift = e => {
		uni.$emit('showGift', JSON.parse(e))
	}

	const fto = () => {
		uni.navigateTo({
			url: '/pages/my/wallet'
		})
	}
</script>
<style lang="scss" scoped>
	.heart {
		height: 50rpx !important;
	}
</style>
<style lang="scss" scoped src="./style/index.scss"></style>